package com.ktgj.flight.util;

import com.ktgj.flight.domain.FlightAdjust;
import com.ktgj.flight.domain.vo.DocumentVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class UploadFile {
//    @Value("${file.uploadDocument-avatar}")
//    private String uploadDocument;
    /**
     * 上传文件到服务器
     * @param file 文件流
     * @return
     */
    public DocumentVo document(MultipartFile file) {
        DocumentVo documentVo = new DocumentVo();
//        String destFilePath = uploadDocument;
        String destFilePath = "D:\\ktgj\\FlightAdjust";
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            String fileName = file.getOriginalFilename();
            String[] split = fileName.split("\\.");
            inputStream = file.getInputStream();
            // 数据缓冲
            byte[] buffer = new byte[1024 * 1024];
            //读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
            File tempFile = new File(destFilePath);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            //重新命名
            fileName = UUID.randomUUID().toString() +"."+ split[split.length-1];
            fileOutputStream = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
            // 开始读取
            while ((len = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }

            documentVo.setFile(tempFile);
            documentVo.setUrl(destFilePath + "\\" + fileName);
            return documentVo;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                fileOutputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
